//
//  BaseTabBarViewController.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/5/11.
//

import UIKit

#if canImport(SnapKit)
import SnapKit

class BaseTabBarViewController: UITabBarController {
    
    // 自定义Tabbar高度
    var customTabBarHeight : CGFloat{
        get{
            return 0
        }
    }
    
    override func setViewControllers(_ viewControllers: [UIViewController]?, animated: Bool) {
        super.setViewControllers(viewControllers, animated: animated)
        
        self.customTabBar.reloadData()
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //隐藏系统默认TabBar
        self.tabBar.isHidden = true
    }
    @available(iOS 11.0, *)
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        
        self.customTabBar.snp.updateConstraints { make in
            make.height.equalTo(self.customTabBarHeight + self.view.safeAreaInsets.bottom)
        }
    }
    lazy var customTabBar: CustomTabBar = {
        
        let tabBar = CustomTabBar()
        tabBar.delegate = self
        self.view.addSubview(tabBar)
        tabBar.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(self.customTabBarHeight)
        }

        return tabBar
    }()
    
    /// 切换Tabbar
    /// - Parameter index: ~
    func switchTabbar(to index:Int){
        
        self.selectedIndex = index
        self.customTabBar.setSelected(at: index)
    }
    
    //MARK: 通过继承方式并重写以下方法，实现自定义BaseTabBarControllewr
    
    /// TabBarItem的大小
    /// - Parameter index: 序号
    /// - Returns: ~
    func sizeForTabBarItemAt(_ index:Int) -> CGSize{
        return .zero
    }
    
    /// TabBar的视图控件，不支持其它点击事件相关
    /// - Parameter index: 序号
    /// - Returns: ~
    func viewForTabBarItemAt(_ index:Int) -> UIControl{
        return UIControl()
    }
    
    /// TabBarItem布局在TabBar上的边距
    /// - Returns: ~
    func insetForCustomTabBar() -> UIEdgeInsets{
        return .zero
    }
    
    /// 点击tabbar事件
    /// - Parameters:
    ///   - index: 序号
    ///   - customTabbarView: 返回自定义的tabbarBtn
    /// - Returns: 是否点击有效
    func selectedCustomTabbar(at index:Int ,customTabbarView:UIView?) -> Bool{
        return false
    }
}
//MARK: 实现自定义TabBar协议
extension BaseTabBarViewController : CustomTabbarDelegate{
    
    func numberOfTabBarItems(in customTabBar: CustomTabBar) -> Int? {
        
        return self.viewControllers?.count
    }
    func insetOfTabBar(_ customTabBar: CustomTabBar) -> UIEdgeInsets {
        
        return self.insetForCustomTabBar()
    }
    func customTabBar(_ customTabBar: CustomTabBar, didSelectedArragedSubviewAt index: Int, customTabbarView: UIControl?) -> Bool {
        
        guard self.selectedCustomTabbar(at: index,customTabbarView: customTabbarView) else {
            return false
        }
        self.selectedIndex = index
        return true
    }
    func customTabBar(_ customTabBar: CustomTabBar, sizeForTabBarArragedSubviewAt index: Int) -> CGSize {
        
        return self.sizeForTabBarItemAt(index)
    }
    func customTabBar(_ customTabBar: CustomTabBar, viewForTabBarArragedSubviewAt index: Int) -> UIControl {
        
        return self.viewForTabBarItemAt(index)
    }
}
//MARK: 自定义TabBar协议
protocol CustomTabbarDelegate : NSObject{
    
    func numberOfTabBarItems(in customTabBar:CustomTabBar) -> Int?
    
    func insetOfTabBar(_ customTabBar:CustomTabBar) -> UIEdgeInsets
    
    func customTabBar(_ customTabBar:CustomTabBar, viewForTabBarArragedSubviewAt index:Int) -> UIControl
    
    func customTabBar(_ customTabBar:CustomTabBar, sizeForTabBarArragedSubviewAt index:Int) -> CGSize
    
    func customTabBar(_ customTabBar:CustomTabBar, didSelectedArragedSubviewAt index:Int,customTabbarView:UIControl?) -> Bool
}
//MARK: 自定义TabBar
class CustomTabBar : UIView{
   
    weak var delegate : CustomTabbarDelegate?
    
    lazy var tabBarStackView: UIStackView = {
        
        let view = UIStackView()
        view.axis = .horizontal
        view.distribution = .equalCentering
        view.alignment = .top
        view.spacing = 0
        self.addSubview(view)
        view.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(self.safeAreaLayoutGuide)
            } else {
                make.bottom.equalToSuperview()
            }
        }
        return view
    }()
    
    func reloadData(){
        
        guard let delegate = self.delegate else {
            return
        }
        guard let tabBarNum = delegate.numberOfTabBarItems(in: self) else {
            return
        }
        
        let inset = delegate.insetOfTabBar(self)
        self.tabBarStackView.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(inset.left)
            make.right.equalToSuperview().offset(-inset.right)
            make.top.equalToSuperview().offset(inset.top)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(self.safeAreaLayoutGuide).offset(-inset.bottom)
            } else {
                make.bottom.equalToSuperview().offset(-inset.bottom)
            }
        }
        
        self.clearStackViews()
        for index in 0..<tabBarNum {
            
            let size = delegate.customTabBar(self, sizeForTabBarArragedSubviewAt: index)
            let tabBarItems = delegate.customTabBar(self, viewForTabBarArragedSubviewAt: index)
            tabBarItems.addTarget(self, action: #selector(selectedTabBarItemsEvent(_:)), for: .touchUpInside)
            tabBarItems.tag = 1000 + index
            self.tabBarStackView.addArrangedSubview(tabBarItems)
            tabBarItems.snp.makeConstraints { make in
                make.size.equalTo(size)
            }
        }
    }
    @objc func selectedTabBarItemsEvent(_ item:UIControl){
        
        guard let delegate = self.delegate else {
            return
        }
        let index = item.tag - 1000
        let isSelected = delegate.customTabBar(self, didSelectedArragedSubviewAt: index, customTabbarView: item)
        if isSelected{
            self.resetStackViews()
        }
        item.isSelected = isSelected
    }
    
    func setSelected(at index:Int){
        
        guard self.tabBarStackView.arrangedSubviews.count > index else {
            return
        }
        guard let subView = self.tabBarStackView.arrangedSubviews[index] as? UIControl else {
            return
        }
        self.resetStackViews()
        subView.isSelected = true
    }
    //重置
    func resetStackViews(){
        for arragedView in self.tabBarStackView.arrangedSubviews{
            
            guard let arragedView = arragedView as? UIControl else {
                continue
            }
            arragedView.isSelected = false
        }
    }
    /// 清除所有已添加的按钮
    func clearStackViews(){
        
        self.tabBarStackView.clearArrangedSubviews()
    }
}
#endif
